package com.xiaodu.springboot.mybatis.plus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author: dutianjie
 * @date: 2021/5/10
 * @version: v1.0.0
 * @description: 描述
 **/
@Configuration
public class MybatisPlusConfig {


    // mybatisPlus 分页
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
       MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        paginationInnerInterceptor.setMaxLimit(1000L);
        paginationInnerInterceptor.setOverflow(false);
        // 分页
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        // 乐观锁
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
       return mybatisPlusInterceptor;
    }


    // 字段自动填充功能
    @Bean
    public MetaObjectHandler dateTimeMetaObjectHandler() {
        return new MetaObjectHandler(){

            @Override
            public void insertFill(MetaObject metaObject) {
                // insert
                this.strictInsertFill(metaObject, "gmtCreate",LocalDateTime::now, LocalDateTime.class);
                // update
                this.strictUpdateFill(metaObject, "gmtModified", LocalDateTime::now, LocalDateTime.class);
                // del 逻辑删除字段默认值
                this.strictInsertFill(metaObject, "del",() -> 2, Integer.class);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.strictUpdateFill(metaObject, "gmtModified", LocalDateTime::now, LocalDateTime.class);
            }
        };
    }

}
